/**
 * 
 */
package com.lmm.car;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.codec.binary.Base64;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.StatusLine;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpResponseException;
import org.apache.http.client.ResponseHandler;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.client.methods.RequestBuilder;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import com.lmm.http.client.HttpClientUtils2;
import com.lmm.rsa.RSAScriptEngine;

/**
 * 登录汽车之家
 * @author leiming
 *
 */
public class LoginAutoHome {
	
	public static final String userName = "中拓瑞博";
	public static final String password = "ZTRB060708#";
	
	/**
	 * @param args
	 * @throws Exception 
	 */
	public static void main(String[] args) throws Exception {
		/*boolean islogin  = login();
		if(islogin){
			System.out.println("登录成功。");
		}else {
			System.out.println("登录失败。");
		}*/
		/*String imgBase64  = getDealerValidateCode();
		System.out.println(imgBase64);*/

	}
	
	/**
	 * 
	 * 
	 * */
	public static String login(String requestVerificationToken,
			String rkey,String username,String enPassword,
			String checkCodeDealer) throws Exception{
		CloseableHttpClient httpclient = HttpClientUtils2.getHttpClient();
		List<NameValuePair> listParameter = new ArrayList<NameValuePair>();
    	listParameter.add(new BasicNameValuePair("__RequestVerificationToken", requestVerificationToken));
    	listParameter.add(new BasicNameValuePair("UserNameDealer", username));
    	listParameter.add(new BasicNameValuePair("PasswordDealer", enPassword));
    	listParameter.add(new BasicNameValuePair("RedisKey",rkey));
    	listParameter.add(new BasicNameValuePair("checkCodeDealer", checkCodeDealer));
    	@SuppressWarnings("deprecation")
		HttpEntity entityP = new UrlEncodedFormEntity(listParameter, HTTP.UTF_8);
        HttpUriRequest login = RequestBuilder.post()
                .setUri("http://ics.autohome.com.cn/passport/")
                .setEntity(entityP)
                .build();
        login.setHeader("Accept", "*/*");
        login.setHeader("X-Requested-With","XMLHttpRequest");
        login.setHeader("Accept-Language", "zh-CN,zh;q=0.8");
        login.setHeader("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
        login.setHeader("Referer", "http://ics.autohome.com.cn/passport/account/login");
        login.setHeader("User-Agent", HttpClientUtils2.userAgent);
        String content  = httpclient.execute(login,HttpClientUtils2.basicResponseHandler);
        return content;
	}
	

	public static boolean login() throws Exception{
			CloseableHttpClient httpclient = HttpClientUtils2.getHttpClient(); 
        	HttpGet httpget = new HttpGet("http://ics.autohome.com.cn/passport/account/login");
            httpget.setHeader("User-Agent", HttpClientUtils2.userAgent);
            String content  = httpclient.execute(httpget,HttpClientUtils2.basicResponseHandler);
            Document doc =  Jsoup.parse(content);
            String tag = "#divDealer>form>input[name=__RequestVerificationToken]";
            Elements els =  doc.select(tag);
            Element e = els.first();
            String __RequestVerificationToken = e.attr("value");
            //加密参数
            tag = "#hidPublicKeyExponent";
            String publicKeyExponent = doc.select(tag).first().attr("value");
            tag = "#hidPublicKeyModulus";
            String publicKeyModulus = doc.select(tag).first().attr("value");
            tag = "#rkey";
            String rkey = doc.select(tag).first().attr("value");
           
            String passwordDealer =RSAScriptEngine.encryptedString(publicKeyExponent, publicKeyModulus, password);
        	List<NameValuePair> listParameter = new ArrayList<NameValuePair>();
        	listParameter.add(new BasicNameValuePair("__RequestVerificationToken", __RequestVerificationToken));
        	listParameter.add(new BasicNameValuePair("UserNameDealer", userName));
        	listParameter.add(new BasicNameValuePair("PasswordDealer", passwordDealer));
        	listParameter.add(new BasicNameValuePair("RedisKey",rkey));
        	listParameter.add(new BasicNameValuePair("checkCodeDealer", ""));
        	@SuppressWarnings("deprecation")
			HttpEntity entityP = new UrlEncodedFormEntity(listParameter, HTTP.UTF_8);
            HttpUriRequest login = RequestBuilder.post()
                    .setUri("http://ics.autohome.com.cn/passport/")
                    .setEntity(entityP)
                    .build();
            login.setHeader("Accept", "*/*");
            login.setHeader("X-Requested-With","XMLHttpRequest");
            login.setHeader("Accept-Language", "zh-CN,zh;q=0.8");
            login.setHeader("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
            login.setHeader("Referer", "http://ics.autohome.com.cn/passport/account/login");
            login.setHeader("User-Agent", HttpClientUtils2.userAgent);
            content  = httpclient.execute(login,HttpClientUtils2.basicResponseHandler);
            if("0".equals(content)){
            	return true;
            }
            return false;
            
	}

	/**
	 * 获取登录初始化参数
	 * @return
	 * @throws IOException 
	 * @throws ClientProtocolException 
	 */
	public static Map<String,String> getInitParameter() throws ClientProtocolException, IOException{
		Map<String,String> param = new HashMap<String, String>();
		CloseableHttpClient httpclient = HttpClientUtils2.getHttpClient(); 
		HttpGet httpget = new HttpGet("http://ics.autohome.com.cn/passport/account/login");
        httpget.setHeader("User-Agent", HttpClientUtils2.userAgent);
        String content  = httpclient.execute(httpget,HttpClientUtils2.basicResponseHandler);
        Document doc =  Jsoup.parse(content);
        String tag = "#divDealer>form>input[name=__RequestVerificationToken]";
        Elements els =  doc.select(tag);
        Element e = els.first();
        String __RequestVerificationToken = e.attr("value");
        //加密参数
        tag = "#hidPublicKeyExponent";
        String publicKeyExponent = doc.select(tag).first().attr("value");
        tag = "#hidPublicKeyModulus";
        String publicKeyModulus = doc.select(tag).first().attr("value");
        tag = "#rkey";
        String rkey = doc.select(tag).first().attr("value");
        param.put("__RequestVerificationToken", __RequestVerificationToken);
        param.put("hidPublicKeyExponent", publicKeyExponent);
        param.put("hidPublicKeyModulus", publicKeyModulus);
        param.put("rkey", rkey);
        return param;
	}
	
	/**
	 * 获取汽车之家验证码图片Base64编码字符串
	 * @return
	 * @throws  
	 * @throws Exception 
	 */
	public static String getDealerValidateCode() throws Exception{
		CloseableHttpClient httpclient = HttpClientUtils2.getHttpClient(); 
		HttpGet httpget = new HttpGet("http://ics.autohome.com.cn/passport/Account/GetDealerValidateCode?time="+new Date().getTime());
        httpget.setHeader("User-Agent", HttpClientUtils2.userAgent);
        String content  = httpclient.execute(httpget,new ResponseHandler<String>() {

			@Override
			public String handleResponse(HttpResponse response)
					throws ClientProtocolException, IOException {
				final StatusLine statusLine = response.getStatusLine();
		        final HttpEntity entity = response.getEntity();
		        if (statusLine.getStatusCode() >= 300) {
		            EntityUtils.consume(entity);
		            throw new HttpResponseException(statusLine.getStatusCode(),
		                    statusLine.getReasonPhrase());
		        }
		        byte[] binaryData =( entity == null ? null : EntityUtils.toByteArray(entity));
		         String imgBase64 = Base64.encodeBase64String(binaryData);
		         StringBuffer sb = new StringBuffer();
		         sb.append("data:image/jpg;base64,");
		         sb.append(imgBase64);
		        //String imgBase64 = Base64.encodeBase64URLSafeString(binaryData);
		        return sb.toString();
			}
        	
		});
        return content;
	}
}
